package com.moxiao.yfjh.module.member.dal.mysql.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.mybatis.core.mapper.BaseMapperX;
import com.moxiao.yfjh.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.moxiao.yfjh.module.member.controller.admin.user.vo.MemberUserPageReqVO;
import com.moxiao.yfjh.module.member.controller.admin.user.vo.MemberUserRespVO;
import com.moxiao.yfjh.module.member.controller.app.user.vo.AppTeamReqVo;
import com.moxiao.yfjh.module.member.dal.dataobject.user.MemberUserDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员 User Mapper
 *
 * @author mx
 */
@Mapper
public interface MemberUserMapper extends BaseMapperX<MemberUserDO> {

    default MemberUserDO selectByMobile(String mobile) {
        return selectOne(MemberUserDO::getMobile, mobile);
    }

    default List<MemberUserDO> selectListByNicknameLike(String nickname) {
        return selectList(new LambdaQueryWrapperX<MemberUserDO>()
                .likeIfPresent(MemberUserDO::getNickname, nickname));
    }

    default PageResult<MemberUserDO> selectPage(MemberUserPageReqVO reqVO) {
        // 处理 tagIds 过滤条件
        String tagIdSql = "";
        if (CollUtil.isNotEmpty(reqVO.getTagIds())) {
            tagIdSql = reqVO.getTagIds().stream()
                    .map(tagId -> "FIND_IN_SET(" + tagId + ", tag_ids)")
                    .collect(Collectors.joining(" OR "));
        }
        // 分页查询
        return selectPage(reqVO, new LambdaQueryWrapperX<MemberUserDO>()
                .likeIfPresent(MemberUserDO::getMobile, reqVO.getMobile())
                .betweenIfPresent(MemberUserDO::getLoginDate, reqVO.getLoginDate())
                .likeIfPresent(MemberUserDO::getNickname, reqVO.getNickname())
                .betweenIfPresent(MemberUserDO::getCreateTime, reqVO.getCreateTime())
                .eqIfPresent(MemberUserDO::getLevelId, reqVO.getLevelId())
                .eqIfPresent(MemberUserDO::getGroupId, reqVO.getGroupId())
                .apply(StrUtil.isNotEmpty(tagIdSql), tagIdSql)
                .orderByDesc(MemberUserDO::getId));
    }

    default Long selectCountByGroupId(Long groupId) {
        return selectCount(MemberUserDO::getGroupId, groupId);
    }

    default Long selectCountByLevelId(Long levelId) {
        return selectCount(MemberUserDO::getLevelId, levelId);
    }

    default Long selectCountByTagId(Long tagId) {
        return selectCount(new LambdaQueryWrapperX<MemberUserDO>()
                .apply("FIND_IN_SET({0}, tag_ids)", tagId));
    }

    /**
     * 更新用户积分（增加）
     *
     * @param id        用户编号
     * @param incrCount 增加积分（正数）
     */
    default void updatePointIncr(Long id, Integer incrCount) {
        Assert.isTrue(incrCount > 0);
        LambdaUpdateWrapper<MemberUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<MemberUserDO>()
                .setSql(" point = point + " + incrCount)
                .eq(MemberUserDO::getId, id);
        update(null, lambdaUpdateWrapper);
    }

    /**
     * 更新用户积分（减少）
     *
     * @param id        用户编号
     * @param incrCount 增加积分（负数）
     * @return 更新行数
     */
    default int updatePointDecr(Long id, Integer incrCount) {
        Assert.isTrue(incrCount < 0);
        LambdaUpdateWrapper<MemberUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<MemberUserDO>()
                .setSql(" point = point + " + incrCount) // 负数，所以使用 + 号
                .eq(MemberUserDO::getId, id);
        return update(null, lambdaUpdateWrapper);
    }


    /**
     * 通过分销员来查询分销员的下属团队
     */
    @Select(" SELECT t.id user_id,t.nickname,t.avatar,t.create_time,t1.price as commission" +
            " FROM blind_member_user t" +
            " LEFT JOIN blind_brokerage_record t1 on t1.source_user_id = t.id" +
            " WHERE distributors = #{distributors}")
    List<AppTeamReqVo> getTeamList(@Param("distributors") String distributors);

    /**
     * 关联分页查询
     * 分销员
     */
    IPage<MemberUserRespVO> getDistributorsList(Page<?> page, @Param("mobile") String mobile, @Param("nickname") String nickname);

    /**
     * 获得团队人数
     *
     * @param userId
     * @return
     */
    @Select("select count(*) from blind_member_user where distributors = #{userId}")
    Integer getTeam(@Param("userId") String userId);

    /**
     * 分页-团队列表
     */
    @Select("select t.* " +
            " from blind_member_user t" +
            " where t.distributors = #{userId}")
    IPage<MemberUserRespVO> getPageTeamList(@Param("userId") String userId);

    /**
     * 分销员累计业绩
     */
    @Select("select IFNULL(sum(t.pay_price),0.00) pay_price" +
            " from blind_trade_order t" +
            " JOIN blind_member_user t1 on t.user_id = t1.id" +
            " where t1.distributors = #{userId}")
    BigDecimal getPerformance(@Param("userId") String userId);
}
